package com.uniknow.app.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.ContactsContract;

import com.uniknow.app.bin.TBFriend;
import com.uniknow.app.bin.TBFriendTmp;
import com.uniknow.app.util.StringUtils;

public class FriendManager extends BaseManager<TBFriend>{
	final static Uri Contacts_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;//ContactsContract.Contacts.CONTENT_URI;
	
	private BaseManager<TBFriendTmp> friendTmpManager;

	public FriendManager(Context context, Class<TBFriend> clazz) {
		super(context, clazz);
		friendTmpManager = new BaseManager<TBFriendTmp>(mContext, TBFriendTmp.class);
	}
	
	/**
	 * 对临时表中的tel进行分组，重复只记录一次。主要屏蔽有的人，sim卡和phone都有记录
	 * @author lianjiao 
	 * @created 2013-12-23
	 * @param db
	 * @return
	 */
	public ArrayList<TBFriend> FixTmpBeforeInsert(){
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		ArrayList<TBFriend> FriendListFix = new ArrayList<TBFriend>();
		TBFriend tbFriendTmp;
		Cursor cursor = db.rawQuery("select * from "+dataBaseHelper.getTableName(TBFriendTmp.class)+" group by phone_number order by _id", null);
		while(cursor.moveToNext()){
			tbFriendTmp = new TBFriend();
			tbFriendTmp.setYunzhi_id(cursor.getString(1));
			tbFriendTmp.setPhone_number(cursor.getString(2));tbFriendTmp.setPhone_number1(cursor.getString(3));tbFriendTmp.setPhone_number2(cursor.getString(4));tbFriendTmp.setPhone_number3(cursor.getString(5));tbFriendTmp.setReal_name(cursor.getString(6));tbFriendTmp.setNice_name(cursor.getString(7));tbFriendTmp.setImei(cursor.getString(8));
			tbFriendTmp.setQq(cursor.getString(9));tbFriendTmp.setWix(cursor.getString(10));tbFriendTmp.setSina(cursor.getString(11));
			tbFriendTmp.setHot(cursor.getInt(12));tbFriendTmp.setAvg(cursor.getInt(13));tbFriendTmp.setWarning(cursor.getInt(14));
			
			tbFriendTmp.setPhone_contacted_last_time(cursor.getInt(15));
			tbFriendTmp.setPhone_contacted_count(cursor.getInt(16));
			tbFriendTmp.setPhone_contacted_at_time(cursor.getInt(17));
			tbFriendTmp.setPhone_contacted_at_time_amplitude(cursor.getInt(18));
			
			tbFriendTmp.setNet_contacted_last_time(cursor.getInt(19));
			tbFriendTmp.setNet_contacted_count(cursor.getInt(20));
			tbFriendTmp.setNet_contacted_at_time(cursor.getInt(21));
			tbFriendTmp.setNet_contacted_at_time_amplitude(cursor.getInt(22));
			
			tbFriendTmp.setLevel(cursor.getInt(23));tbFriendTmp.setLevel_request(cursor.getInt(24));tbFriendTmp.setLevel_response(cursor.getInt(25));
			FriendListFix.add(tbFriendTmp);
		}
		db.delete(dataBaseHelper.getTableName(TBFriendTmp.class), null, null);
		return FriendListFix;
		
	}
	
	/**
	 * 插入好友信息到好友表,第一次初始化插入的时候
	 * @author lianjiao 
	 * @created 2013-12-23
	 * @param FriendList
	 * @param db
	 * @param istmp 是否为临时表
	 */
	public void InsertFriend(ArrayList<TBFriend> FriendList,boolean istmp){
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		String tname = dataBaseHelper.getTableName(TBFriendTmp.class);
		if(!istmp){
			tname = dataBaseHelper.getTableName(TBFriend.class);
		}else{
			//tmp表进行清空处理
			db.delete(dataBaseHelper.getTableName(TBFriendTmp.class), null, null);
			//dataBaseHelper.deltetDate(TBFriendTmp.class);
		}
		db.beginTransaction();
		try{
			for(TBFriend friend :FriendList){
				db.execSQL(
						"INSERT INTO " + tname + 
						"(yunzhi_id,phone_number,phone_number1,phone_number2,phone_number3,real_name,nice_name,imei," +
								
						"qq,wix,sina," +
						
						"hot,avg,warning," +
						
						"phone_contacted_last_time," +
						"phone_contacted_count," +
						"phone_contacted_at_time," +
						"phone_contacted_at_time_amplitude," +
						
						"net_contacted_last_time," +
						"net_contacted_count," +
						"net_contacted_at_time," +
						"net_contacted_at_time_amplitude," +
						
						"level," +
						"level_request," +
						"level_response) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
						new Object[]{
							friend.getYunzhi_id(),friend.getPhone_number(),friend.getPhone_number1(),friend.getPhone_number2(),friend.getPhone_number3(),friend.getReal_name(),friend.getNice_name(),friend.getImei(),
							friend.getQq(),friend.getWix(),friend.getSina(),
							friend.getHot(),friend.getAvg(),friend.getWarning(),
							
							friend.getPhone_contacted_last_time(),
							friend.getPhone_contacted_count(),
							friend.getPhone_contacted_at_time(),
							friend.getPhone_contacted_at_time_amplitude(),
							
							friend.getNet_contacted_last_time(),
							friend.getNet_contacted_count(),
							friend.getNet_contacted_at_time(),
							friend.getNet_contacted_at_time_amplitude(),
							
							friend.getLevel(),friend.getLevel_request(),friend.getLevel_response()}
						);
				}
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
		}

	}
	
	
	/**
	 * 从联系人表中获取仅有电话号码的好友，并且存储最后一次联系时间
	 * @author lianjiao 
	 * @created 2013-11-13
	 */
	public ArrayList<TBFriend> GetFriendListFromContacts(){
		ArrayList<TBFriend> FriendList = new ArrayList<TBFriend>();
		String[] selectParam = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER,ContactsContract.CommonDataKinds.Phone.LAST_TIME_CONTACTED};// String[] projection==>*
		ContentResolver cr = mContext.getContentResolver();
		final Cursor cursor = cr.query(Contacts_URI,// uri==>from.table
				selectParam,// String[] projection==>*
				ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER+">?",// String selection==>where.field
				new String[]{"0"},// String[] selectionArgs==>where.param
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" COLLATE LOCALIZED ASC");// 排序字段==>order by//ContactsContract.Contacts.DISPLAY_NAME  + " COLLATE LOCALIZED ASC"
		if (cursor != null) {
			while (cursor.moveToNext()) {
				TBFriend friend = new TBFriend();
				friend.setReal_name(cursor.getString(0));
				friend.setPhone_number(cursor.getString(1));
				friend.setPhone_number1(cursor.getString(2));
				friend.setPhone_contacted_last_time(cursor.getInt(4));
				FriendList.add(friend);
			}
			cursor.close();
		}
		return FriendList;
	}
	/**
	 * 根据数据，设置TBFriend表的Hot值
	 * @author lianjiao 
	 * @created 2013-12-19
	 * @param FriendList
	 * @param db
	 */
	public void SetHotValue(HashMap<String,Integer> FriendHM){
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		HashMap<String,Integer> FriendHM2 = new HashMap<String,Integer>();
		//处理IP拨号的
		Iterator iterator=FriendHM.entrySet().iterator();
		while(iterator.hasNext()) {
			Entry<String,Integer> entry = (Entry<String,Integer>)iterator.next();
			String tmpkey = StringUtils.FixTel(entry.getKey());
			int tmpvalue = FriendHM2.get(tmpkey)==null?0:FriendHM2.get(tmpkey);
			if(tmpvalue>0){
				FriendHM2.put(tmpkey,tmpvalue+entry.getValue());
			}else{
				FriendHM2.put(tmpkey,entry.getValue());
			}
			
		}
		Iterator iterator2=FriendHM2.entrySet().iterator();
		db.beginTransaction();
		try{
			while(iterator2.hasNext()) {
				@SuppressWarnings("unchecked")
				Entry<String,Integer> entry = (Entry<String,Integer>)iterator2.next();
				entry.getKey();
				entry.getValue();
				db.execSQL("update "+dataBaseHelper.getTableName(TBFriend.class)+" set hot = hot+"+entry.getValue()+" where phone_number='"+entry.getKey()+"' or phone_number1='"+entry.getKey()+"' or phone_number2='"+entry.getKey()+"' or phone_number3='"+entry.getKey()+"'");
			}
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
		}
		
	}
	
	public ArrayList<TBFriend> FindHotList(){
		ArrayList<TBFriend> HotList = new ArrayList<TBFriend>();
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		final Cursor cursor = db.rawQuery("select _id,phone_number,real_name,hot from "+dataBaseHelper.getTableName(TBFriend.class)+" order by hot desc",null);
		int Top = 10,count=0;
		if (cursor != null) {
			while (cursor.moveToNext()&&count<Top) {
				TBFriend friend = new TBFriend();
				//friend.set_id(cursor.getString(0));//好像是有微博帐号在其中，导致不能用int，必须用string类型的吧
				friend.set_id(cursor.getInt(0));//好像是有微博帐号在其中，导致不能用int，必须用string类型的吧
				friend.setPhone_number(cursor.getString(1));
				friend.setReal_name(cursor.getString(2));
				friend.setHot(cursor.getInt(3));
				HotList.add(friend);
				count++;
				System.out.println("tel = "+friend.getPhone_number()+" name = "+friend.getReal_name());
			}
		}
		return HotList;
	}

}
